<template>
  <el-card class="box-card">
    <el-form :inline="true" :model="pagination" class="demo-form-inline">
      <el-form-item>
        <el-input
          v-model.trim="pagination.searchObj"
          placeholder="用户名"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onSubmit"
          icon="el-icon-search"
          size="small "
          >查询</el-button
        >
        <el-button @click="empty" size="small">清空</el-button>
      </el-form-item>
    </el-form>

    <div class="mb">
      <el-button @click="addUserList" type="primary" size="small ">添加</el-button>
      <el-button @click="BatchHadler" size="small" type="danger" :disabled="multipleSelection.length == 0"
        >批量删除</el-button
      >
    </div>
    <!--       @selection-change="handleSelectionChange"  -->
    <el-table
      ref="multipleTable"
      tooltip-effect="dark"
      style="width: 100%"
      border
      :data="userList"
      @selection-change="deleteSelectionChange"
    >
      <el-table-column type="selection" width="55" fixed="left" align="center">

      </el-table-column>
      <el-table-column type="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="100px">
      </el-table-column>
      <el-table-column
        prop="nickName"
        label="用户昵称"
        show-overflow-tooltip
        width="140px"
      >
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色列表"
        show-overflow-tooltip
        width="140px"
      >
      </el-table-column>
      <el-table-column
        prop="gmtCreate"
        label="创建时间"
        show-overflow-tooltip
        width="200px"
      >
      </el-table-column>
      <el-table-column
        prop="gmtModified"
        label="更新时间"
        show-overflow-tooltip
        width="200px"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        show-overflow-tooltip
        fixed="right"
        width="240px"
      >
        <template v-slot="{ row, $index }">
          <el-button
            size="mini"
            type="info"
            icon="el-icon-user-solid"
            @click="handleSolid(row, $index)"
          ></el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleEdit(row, $index)"
          ></el-button>
          <el-popconfirm
            :title="`确定删除[${row.username}]吗？`"
            class="ml"
            @confirm="handleDeleteHome(row)"
          >
            <el-button
              slot="reference"
              size="mini"
              type="danger"
              icon="el-icon-delete"
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="[6, 12, 18, 24]"
      :page-size="pagination.limit"
      layout=" prev, pager, next, jumper, ->, total, sizes "
      :total="pagination.total"
    >
    </el-pagination>

    <!-- 个人信息弹窗 -->
    <el-dialog title="设置角色" :visible.sync="information">
      <el-form :model="personalInfo">
        <el-form-item label="用户名" label-width="120px">
          <el-input
            v-model="personalInfo.username"
            autocomplete="off"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色列表" label-width="120px">
          <template v-slot="">
            <el-checkbox
              :indeterminate="personalInfo.isIndeterminate"
              v-model="personalInfo.checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0"></div>
            <el-checkbox-group
              v-model="personalInfo.assignRoles"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="city in personalInfo.allRolesList"
                :label="city"
                :key="city"
                >{{ city }}</el-checkbox
              >
            </el-checkbox-group>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="information = false">取 消</el-button>
        <el-button type="primary" @click="distribution">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog :title="formList.id?'修改用户名':'添加用户'" :visible.sync="dialogFormVisible">
      <el-form :model="formList">
        <el-form-item label="用户名" label-width="120px">
          <el-input v-model="formList.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="120px">
          <el-input v-model="formList.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" label-width="120px" v-if="!formList.id">
          <el-input v-model="formList.password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editHadlercancel">取 消</el-button>
        <el-button type="primary" @click="editHadler"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import request from "@/api/acl/user";
export default {
  name: "User",
  data() {
    return {
      pagination: {
        page: 1,
        limit: 6,
        total: 0,
        searchObj: "",
      },
      // 初始信息
      userList: [],
      // 分配角色弹窗
      information: false,
      // 个人信息
      personalInfo: {
        checkAll: false,
        username: "",
        allRolesList: [],
        allRolesListId: [],
        assignRoles: [],
        isIndeterminate: true,
      },
      // 编辑弹窗
      dialogFormVisible: false,
      // 编辑信息
      formList: {
        username: "",
        nickName: "",
        password: "",
        id:''
      },
      // 选中角色分配
      CheckRole: {
        userId: "",
        roleId: "",
      },
      // 编辑发送的请求题
      editList:{},
      // 批量删除事件
      multipleSelection:[]
    };
  },
  methods: {
    deleteSelectionChange(val){
      this.multipleSelection.push(val.id);
      if(this.multipleSelection.length){
        this.Batchdeletion = false
      }
      console.log(val);
    },
    async BatchHadler(){
      this.$confirm('确定删除吗?').then(async () => {
        const result = await request.removeUsers(this.multipleSelection)
        this.$message.success('删除成功')
        this.getUserInfo(this.pagination.page, this.pagination.limit, {
          username: this.pagination.searchObj,
        });
      }).catch(() => {
        this.$message.info('取消删除')
      })
    },
    // 点击新增
    addUserList(){
      this.dialogFormVisible = true
    },
    // 点击删除
    async handleDeleteHome(row){
      try {
        await request.removeById(row.id)
        this.$message.success('删除成功')
        this.getUserInfo(this.pagination.page, this.pagination.limit, {
          username: this.pagination.searchObj,
        });
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
    // 点击编辑
    handleEdit(row, idx) {
      this.formList.username = row.username;
      this.formList.nickName = row.nickName;
      this.formList.id = row.id
      this.dialogFormVisible = true;
      this.editList = row
    },
    // 点击编辑确定
    async editHadler(){
      this.editList.username = this.formList.username
      this.editList.nickName = this.formList.nickName
      try {
        if(!this.formList.id){
          await request.add(this.formList)
        }else{

          await request.update(this.editList);
          
        }
        this.$message.success('编辑成功')
          this.dialogFormVisible = false
          this.getUserInfo(this.pagination.page, this.pagination.limit, {
            username: this.pagination.searchObj,
          });
          this.formList = {}
      } catch (error) {
        console.log(error);
      }
    },
    // 点击编辑取消
    editHadlercancel(){
      this.dialogFormVisible = false
      this.formList = {}
    },
    // 点击查询
    async onSubmit() {
      this.getUserInfo(1);
    },
    // 点击清除
    empty() {
      this.pagination.searchObj = "";
      this.getUserInfo(1);
    },
    // 点击查看个人信息
    async handleSolid(row) {
      this.information = true;
      this.personalInfo.username = row.username;
      this.CheckRole.userId = row.id;
      try {
        let result = await request.getRoles(row.id);
        let { allRolesList, assignRoles } = result.data;
        this.personalInfo.allRolesList = allRolesList.map(
          (item) => item.roleName
        );
        this.personalInfo.assignRoles = assignRoles.map(
          (item) => item.roleName
        );
        this.personalInfo.allRolesListId = allRolesList;
      } catch (error) {
        console.log("查看个人信息失败");
      }
    },
    // 个人弹窗全选
    handleCheckAllChange(val) {
      this.personalInfo.assignRoles = val ? this.personalInfo.allRolesList : [];
      this.personalInfo.isIndeterminate = false;
    },
    // 单个选中
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.personalInfo.checkAll =
        checkedCount === this.personalInfo.allRolesList.length;
      this.personalInfo.isIndeterminate =
        checkedCount > 0 &&
        checkedCount < this.personalInfo.allRolesList.length;
    },
    // 点击保存
    async distribution() {
      let { allRolesListId, assignRoles } = this.personalInfo;
      let res = [];
      allRolesListId.forEach((item) => {
        assignRoles.map((em) => {
          if (item.roleName == em) {
            res.push(item.id);
          }
        });
      });

      try {
        await request.assignRoles(this.CheckRole.userId, res.toString());
        this.information = false;
        this.personalInfo.assignRoles = [];
        this.getUserInfo(this.pagination.page, this.pagination.limit, {
          username: this.pagination.searchObj,
        });
      } catch (error) {
        this.$message.error("保存失败");
      }
    },
    handleSizeChange(val) {
      this.pagination.limit = val;
      this.getUserInfo();
    },
    handleCurrentChange(val) {
      this.pagination.page = val;
      this.getUserInfo();
    },
    // 初始化请求
    async getUserInfo(
      page = this.pagination.page,
      limit = this.pagination.limit
    ) {
      try {
        let result = await request.getPageList(page, limit, {
          username: this.pagination.searchObj,
        });
        this.pagination.total = result.data.total;
        this.userList = result.data.items;
      } catch (error) {
        console.log(error);
        this.$message.error("获取数据失败,请重试");
      }
    },
  },
  mounted() {
    this.getUserInfo();
  },
};
</script>

<style></style>
